package org.jeecg.modules.buildingmanagement.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.buildingmanagement.entity.Picture;
import org.jeecg.modules.buildingmanagement.entity.BuildingManagement;
import org.jeecg.modules.buildingmanagement.vo.BuildingManagementPage;
import org.jeecg.modules.buildingmanagement.service.IBuildingManagementService;
import org.jeecg.modules.buildingmanagement.service.IPictureService;
import org.jeecg.modules.buildingmanagement.vo.BuildingManagementPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 房屋管理
 * @Author: jeecg-boot
 * @Date:   2019-10-09
 * @Version: V1.0
 */
@RestController
@RequestMapping("/buildingManagement")
@Slf4j
public class BuildingManagementController {
	@Autowired
	private IBuildingManagementService buildingManagementService;
	@Autowired
	private IPictureService pictureService;
	
	/**
	  * 分页列表查询
	 * @param buildingManagement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/pageList")
	public Result<List<BuildingManagementPage>> queryPageList(BuildingManagement buildingManagement,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<List<BuildingManagementPage>> result = new Result<List<BuildingManagementPage>>();
		QueryWrapper<BuildingManagement> queryWrapper = QueryGenerator.initQueryWrapper(buildingManagement, req.getParameterMap());
		Page<BuildingManagement> page = new Page<BuildingManagement>(pageNo, pageSize);
		IPage<BuildingManagement> pageList = buildingManagementService.page(page, queryWrapper);
		List<BuildingManagement> buildingList = pageList.getRecords();
		List<BuildingManagementPage> bmpList = new ArrayList<>();
		for (BuildingManagement management : buildingList) {
			Picture picture = new Picture();
			picture.setGroupId(management.getId());
			QueryWrapper<Picture> queryWrapper2 = QueryGenerator.initQueryWrapper(picture, new HashMap<String, String[]>());
			Page<Picture> page2 = new Page<Picture>(pageNo, pageSize);
			IPage<Picture> pageList2 = pictureService.page(page2, queryWrapper2);
			BuildingManagementPage buildingManagementPage = new BuildingManagementPage(management,pageList2.getRecords());
			bmpList.add(buildingManagementPage);

		}

		result.setSuccess(true);
		result.setResult(bmpList);
		return result;
	}

	 /**
	  * 分页列表查询
	  * @param buildingManagement
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @GetMapping("/list")
	 public Result<IPage<BuildingManagement>> queryList(BuildingManagement buildingManagement,
															   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															   HttpServletRequest req) {
		 Result<IPage<BuildingManagement>> result = new Result<IPage<BuildingManagement>>();
		 QueryWrapper<BuildingManagement> queryWrapper = QueryGenerator.initQueryWrapper(buildingManagement, req.getParameterMap());
		 Page<BuildingManagement> page = new Page<BuildingManagement>(pageNo, pageSize);
		 IPage<BuildingManagement> pageList = buildingManagementService.page(page, queryWrapper);

		 result.setSuccess(true);
		 result.setResult(pageList);
		 return result;
	 }
	/**
	  *   添加
	 * @param buildingManagementPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<BuildingManagement> add(@RequestBody BuildingManagementPage buildingManagementPage) {
		Result<BuildingManagement> result = new Result<BuildingManagement>();
		try {
			BuildingManagement buildingManagement = new BuildingManagement();
			BeanUtils.copyProperties(buildingManagementPage, buildingManagement);
			
			buildingManagementService.saveMain(buildingManagement, buildingManagementPage.getPictureList());
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param buildingManagementPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<BuildingManagement> edit(@RequestBody BuildingManagementPage buildingManagementPage) {
		System.out.println(buildingManagementPage);
		Result<BuildingManagement> result = new Result<BuildingManagement>();
		BuildingManagement buildingManagement = new BuildingManagement();
		BeanUtils.copyProperties(buildingManagementPage, buildingManagement);
		BuildingManagement buildingManagementEntity = buildingManagementService.getById(buildingManagement.getId());
		if(buildingManagementEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = buildingManagementService.updateById(buildingManagement);
			buildingManagementService.updateMain(buildingManagement, buildingManagementPage.getPictureList());
			result.success("修改成功!");
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			buildingManagementService.delMain(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<BuildingManagement> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<BuildingManagement> result = new Result<BuildingManagement>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.buildingManagementService.delBatchMain(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<BuildingManagement> queryById(@RequestParam(name="id",required=true) String id) {
		Result<BuildingManagement> result = new Result<BuildingManagement>();
		BuildingManagement buildingManagement = buildingManagementService.getById(id);
		if(buildingManagement==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(buildingManagement);
			result.setSuccess(true);
		}
		return result;
	}

	 /**
	  * 通过id查询 BuildingManagementPage
	  * @param id
	  * @return
	  */
	 @GetMapping(value = "/page/queryById")
	 public Result<BuildingManagementPage> queryPageById(@RequestParam(name="id",required=true) String id,HttpServletRequest req) {
		 Result<BuildingManagementPage> result = new Result<BuildingManagementPage>();
		 BuildingManagement buildingManagement = buildingManagementService.getById(id);
		 Picture picture = new Picture();
		 picture.setGroupId(buildingManagement.getId());
		 QueryWrapper<Picture> queryWrapper2 = QueryGenerator.initQueryWrapper(picture, req.getParameterMap());
		 Page<Picture> page = new Page<Picture>(1, 30);
		 IPage<Picture> pageList = pictureService.page(page, queryWrapper2);
		 BuildingManagementPage buildingManagementPage = new BuildingManagementPage(buildingManagement,pageList.getRecords());
		 if(buildingManagementPage==null) {
			 result.error500("未找到对应实体");
		 }else {
			 result.setResult(buildingManagementPage);
			 result.setSuccess(true);
		 }
		 return result;
	 }
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryPictureByMainId")
	public Result<List<Picture>> queryPictureListByMainId(@RequestParam(name="id",required=true) String id) {
		Result<List<Picture>> result = new Result<List<Picture>>();
		List<Picture> pictureList = pictureService.selectByMainId(id);
		result.setResult(pictureList);
		result.setSuccess(true);
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<BuildingManagement> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              BuildingManagement buildingManagement = JSON.parseObject(deString, BuildingManagement.class);
              queryWrapper = QueryGenerator.initQueryWrapper(buildingManagement, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<BuildingManagementPage> pageList = new ArrayList<BuildingManagementPage>();
      List<BuildingManagement> buildingManagementList = buildingManagementService.list(queryWrapper);
      for (BuildingManagement buildingManagement : buildingManagementList) {
          BuildingManagementPage vo = new BuildingManagementPage();
          BeanUtils.copyProperties(buildingManagement, vo);
          List<Picture> pictureList = pictureService.selectByMainId(buildingManagement.getId());
          vo.setPictureList(pictureList);
          pageList.add(vo);
      }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "房屋管理列表");
      mv.addObject(NormalExcelConstants.CLASS, BuildingManagementPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("房屋管理列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<BuildingManagementPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BuildingManagementPage.class, params);
              for (BuildingManagementPage page : list) {
                  BuildingManagement po = new BuildingManagement();
                  BeanUtils.copyProperties(page, po);
                  buildingManagementService.saveMain(po, page.getPictureList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
